package com.mpaster.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * 定义统一的响应结果
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ResponseResult implements Serializable {

    private int status;
    private String message;
    private Object data;

    public static ResponseResult success() {
        return new ResponseResult(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getDesc(), null);
    }

    public static ResponseResult successMsg(String message) {
        return new ResponseResult(ResponseCode.SUCCESS.getCode(), message, null);
    }

    public static ResponseResult successData(Object data) {
        return new ResponseResult(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getDesc(), data);
    }

    public static ResponseResult success(String message, Object data) {
        return new ResponseResult(ResponseCode.SUCCESS.getCode(), message, data);
    }

    public static ResponseResult error() {
        return new ResponseResult(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc(), null);
    }

    public static ResponseResult errorMsg(String message) {
        return new ResponseResult(ResponseCode.ERROR.getCode(), message, null);
    }

    public static ResponseResult errorData(Object data) {
        return new ResponseResult(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc(), data);
    }

    public static ResponseResult error(String message, Object data) {
        return new ResponseResult(ResponseCode.ERROR.getCode(), message, data);
    }

    public static void responseJson(HttpServletResponse response, String msg) {

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");

        try (PrintWriter pw = response.getWriter()) {
            ResponseResult result = ResponseResult.errorMsg(msg);
//            pw.write(JSONObject.toJSONString(result, SerializerFeature.WriteMapNullValue));
            pw.flush();
        } catch (Exception e) {
//            throw new PTYCoreException("响应出错！");
        }
    }
}
